//
//  Profile.m
//  MyOWNUITableView
//
//  Created by Jordy Heemskerk on 11-05-10.
//  Copyright 2010 ITopia. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "Profile.h"
#import "XMLParser.h"
#import "Category.h"
#import "SubCategory.h"


@implementation Profile


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	appDelegate = (MyOWNUITableViewAppDelegate *) [[UIApplication sharedApplication] delegate];
	
	[UIView setAnimationDelegate:self];
	
	appDelegate.categories = [[NSMutableArray alloc] init];
	
	[NSThread detachNewThreadSelector:@selector(receiveCategories) toTarget:self withObject:nil];	
	
	scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 0, 310, 436)];
	[scrollView setAlwaysBounceVertical:YES];
	[self.view addSubview:scrollView];
	
	
}

- (void)receiveCategories {
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	NSString *urlstr = [[[NSString alloc] initWithFormat:@"%@getCategories.php", [appDelegate baseURL]] autorelease];
	NSURL *url = [[[NSURL alloc] initWithString:urlstr] autorelease];
	NSXMLParser *xmlParser = [[[NSXMLParser alloc] initWithContentsOfURL:url] autorelease];
	
	XMLParser *parser = [[XMLParser alloc] initXMLParser];
	
	[xmlParser setDelegate:parser];
	
	BOOL succes = [xmlParser parse];
	
	if (!succes) {
		NSLog(@"Something went wrong with parsing the XML.. Bummer");
	}
	
	[self buildLayout];
	
	[pool release];
	pool = nil;
	
}

- (void) buildLayout {
	
	categories = [[NSMutableArray alloc] init];
	subCategories = [[NSMutableArray alloc] init];
	int catCount = 0;
	int subCatCount = 0;	
	
	for (Category *cat in [appDelegate categories]) {
		
		UIButton *category = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 + 40 * (catCount + subCatCount) + 20 * catCount, 300, 40)];
		[category setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
		[category.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:32]];
		[category setTitle: [cat name] forState:UIControlStateNormal];
		[category setBackgroundColor:[UIColor whiteColor]];
		[category setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
		[category setTag:catCount];
		[category addTarget:self action:@selector(rebuildLayout:) forControlEvents:UIControlEventTouchUpInside];
		[categories addObject:category];
		[scrollView addSubview:[categories lastObject]];
		
		catCount++;
		
		UIScrollView *subcategories = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20 + 40 * (catCount + subCatCount) + 20 * (catCount - 1), 300, 40 * [[cat subCategories] count])];
		[subcategories setBackgroundColor:[UIColor whiteColor]];
		int i = 0;
		for (SubCategory *sub in [cat subCategories]) {
			UILabel *subCategory = [[UILabel alloc] initWithFrame:CGRectMake(10, 0 + 40 * i, 190, 40)];
			[subCategory setFont:[UIFont fontWithName:@"Helvetica-Bold" size:26]];
			[subCategory setAdjustsFontSizeToFitWidth:YES];
			[subCategory setText:[sub name]];
			
			[subcategories addSubview:subCategory];

			UISwitch *setter = [[UISwitch alloc] initWithFrame:CGRectMake(205, 7 + 40 * i, 0, 0)];
			[setter setOn:[[sub value] boolValue]];
			[setter setTag:[[sub sId] integerValue]];
			[setter addTarget:self action:@selector(toggleSubCat:) forControlEvents:UIControlEventValueChanged];
			[subcategories addSubview:setter];
			
			subCatCount++;
			i++;
			
		}
		[subCategories addObject:subcategories];
		[scrollView addSubview:[subCategories lastObject]];
	
	}
	
	[scrollView setContentSize:CGSizeMake(300,  20 + 40 * (catCount + subCatCount) + 20 * (catCount - 1) + 20)];

	
}

- (void) rebuildLayout: (id) sender {
	UIButton *button = (UIButton *) sender;
	
	int buttonNumber = [button tag];
	
	UIScrollView *subCatView = [subCategories objectAtIndex:buttonNumber];
	
	float height = subCatView.frame.size.height;
	[scrollView sendSubviewToBack:subCatView];
	
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
	[UIView setAnimationDuration:0.5];
	[UIView setAnimationDelegate:self];
	if([subCatView alpha] == 1) {
		[subCatView setAlpha:0];
	} else {
		[subCatView setAlpha:1];
		height *= -1;
	}
	
	for (int i = buttonNumber + 1; i < [appDelegate.categories count]; i++) {
		[[categories objectAtIndex:i] setCenter:CGPointMake([[categories objectAtIndex:i] center].x, [[categories objectAtIndex:i] center].y - height)];
		[[subCategories objectAtIndex:i] setCenter:CGPointMake([[subCategories objectAtIndex:i] center].x, [[subCategories objectAtIndex:i] center].y - height)];
	}
	
	[scrollView setContentSize:CGSizeMake([scrollView contentSize].width, [scrollView contentSize].height - height)];
	
	[UIView commitAnimations];
	
}

- (void) toggleSubCat: (id) sender {
	NSString *urlstr = [[NSString alloc] initWithFormat:@"%@setCategorie.php?did=%@&cid=%i&value=%i", [appDelegate baseURL], [appDelegate deviceid], [sender tag], [NSNumber numberWithBool:[sender isOn]]];
	NSURL *url = [[NSURL alloc] initWithString:urlstr];
	NSString *anwser = [[NSString alloc] initWithContentsOfURL:url];
	NSLog(@"%@", anwser);
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
